package com.ligongmusic.fragment;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.ContentResolver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.provider.MediaStore;
import android.provider.MediaStore.Images;
import android.util.Base64;
import android.view.Display;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.ligongmusic.R;
import com.ligongmusic.adapter.UniversalAdapter;
import com.ligongmusic.adapter.ViewHolder;
import com.ligongmusic.base.BaseFragment;
import com.ligongmusic.domain.MusicInfo;
import com.ligongmusic.util.AudioUtils;
import com.ligongmusic.util.DialogUtils;
import com.ligongmusic.util.DialogUtils.SelectCallBack;
import com.ligongmusic.util.GlobalParams;
import com.ligongmusic.util.ImgUtils;
import com.ligongmusic.util.JsonUtils;
import com.ligongmusic.util.LoggerUtils;
import com.ligongmusic.util.NetWorkUtils;
import com.ligongmusic.util.StringUtils;

public class UploadMusic extends BaseFragment {
	private List<MusicInfo> musicList;
	private View musicListView;
	private AlertDialog dialog, loadDialog;
	private MusicInfo selectMusicInfo;
	private Handler handler = new Handler();
	private TextView fileName, tv_lrc_name;
	private File lrcFile;
	private Bitmap bitmap;
	private Uri uritempFile;
	private boolean isFirst = true;
	private Button submit;

	@Override
	protected View layoutInflater(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		return inflater.inflate(R.layout.upload_music, null);
	}

	@Override
	protected void getData() {
		// TODO Auto-generated method stub
		
	}

	private void showLoading(){
		if (loadDialog == null) {
			loadDialog = new AlertDialog.Builder(getActivity(), R.style.MyDialogStyle).create();
			loadDialog.setCanceledOnTouchOutside(false);
			View pro = View.inflate(getActivity(), R.layout.loading, null);
			loadDialog.setView(pro,0,0,0,0);
			loadDialog.show();
//			dialog.getWindow().setContentView(R.layout.loading);

		}else{
			if (!loadDialog.isShowing())
				loadDialog.show();
		}
	}


	@Override
	public void setUserVisibleHint(boolean isVisibleToUser) {
		super.setUserVisibleHint(isVisibleToUser);
		if (isVisibleToUser && !isFirst) {
            //相当于Fragment的onResume
			initView();
        } else {
            //相当于Fragment的onPause
			if (loadDialog != null && loadDialog.isShowing())
				loadDialog.dismiss();
        }
	}
	
	@Override
	protected void initView() {
		((RelativeLayout)getView(R.id.select_music)).setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				if(musicList == null || musicList.size() == 0)
					musicList = AudioUtils.getMusicList(getActivity());
				selectMusic();
			}
		});
		((RelativeLayout)getView(R.id.rl_music_icon)).setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				DialogUtils.selectDialog(getActivity(), new String[]{"相册", "拍照"}, new SelectCallBack() {
					@Override
					public void select(String item) {
						if (item.contains("相册")){
							Intent intent = new Intent();
							/* 开启Pictures画面Type设定为image */
							intent.setType("image/*");
							intent.setAction(Intent.ACTION_GET_CONTENT);
		//						intent.setAction(MediaStore.ACTION_IMAGE_CAPTURE);
							/* 取得相片后返回本画面 */
							startActivityForResult(intent, 0x2);
						}else {
							Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
							startActivityForResult(cameraIntent, 0x4);
						}
					}
				});
			}
		});
		((RelativeLayout)getView(R.id.rl_singer_status)).setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				DialogUtils.selectDialog(getActivity(), new String[]{"个人", "乐队"}, new SelectCallBack() {
					@Override
					public void select(String item) {
						((TextView)getView(R.id.singer_status)).setText(item);
					}
				});
			}
		});
		((RelativeLayout)getView(R.id.rl_original)).setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				DialogUtils.selectDialog(getActivity(), new String[]{"是", "否"}, new SelectCallBack() {
					@Override
					public void select(String item) {
						((TextView)getView(R.id.tv_original)).setText(item);
					}
				});
			}
		});
		((RelativeLayout)getView(R.id.rl_select_lrc)).setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
				intent.setType("*/*");//设置类型，我这里是任意类型，任意后缀的可以这样写。
				intent.addCategory(Intent.CATEGORY_OPENABLE);
				startActivityForResult(intent,0x1);
//				Intent openAlbumIntent = new Intent(Intent.ACTION_GET_CONTENT);
//				openAlbumIntent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "file/*");
////				startActivityForResult(openAlbumIntent, Activity.RESULT_FIRST_USER);
//				getActivity().startActivityFromFragment(UploadMusic.this, openAlbumIntent, 0x1);
			}
		});
		fileName = getView(R.id.tv_file_name);
		tv_lrc_name = getView(R.id.tv_lrc_name);
		submit = (Button)getView(R.id.bt_submit);
		if (!GlobalParams.isLogin || !GlobalParams.userStatus) {
			submit.setBackgroundResource(R.drawable.upload_gary);
		}else{
			submit.setBackgroundResource(R.drawable.bt_regist_bg);
		}
		submit.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				if (!GlobalParams.isLogin || !GlobalParams.userStatus)
					return;
				String worksName = ((EditText)getView(R.id.et_works_name)).getText().toString().trim();
				if(StringUtils.isEmpty(worksName)){
					Toast.makeText(getActivity(), "请输入作品名称", Toast.LENGTH_SHORT).show();
					return;
				}
				String introduction = ((EditText)getView(R.id.et_introduction)).getText().toString().trim();
				String composer = ((EditText)getView(R.id.et_composer)).getText().toString().trim();
				String producer = ((EditText)getView(R.id.et_producer)).getText().toString().trim();
				String singer_status = ((TextView)getView(R.id.singer_status)).getText().toString().trim();
				String tv_original = ((TextView)getView(R.id.tv_original)).getText().toString().trim();
				
				if(selectMusicInfo == null){
					Toast.makeText(getActivity(), "请选择音乐文件", Toast.LENGTH_SHORT).show();
					return;
				}
				showLoading();
				upload(worksName, introduction, composer, producer, singer_status, tv_original);
			}
		});
		isFirst = false;
	}
	
	private void selectMusic(){
		if(dialog == null){
			musicListView = View.inflate(getActivity(), R.layout.music_list, null);
			Builder builder = new AlertDialog.Builder(getActivity());
			dialog = builder.create();
			dialog.setView(musicListView, 0, 0, 0, 0);
			TextView none_music = (TextView) musicListView.findViewById(R.id.none_music);
			ListView mListView = (ListView) musicListView.findViewById(R.id.lv_music_list);
			if(musicList.size() == 0){
				none_music.setVisibility(View.VISIBLE);
				mListView.setVisibility(View.GONE);
			}else{
				none_music.setVisibility(View.GONE);
				mListView.setVisibility(View.VISIBLE);
				mListView.setAdapter(new UniversalAdapter<MusicInfo>(getActivity(), musicList, R.layout.music_list_item) {
					@Override
					public void convert(ViewHolder holder, MusicInfo t, int position) {
						holder.setText(R.id.music_name, t.getFileName());
					}
				});
				mListView.setOnItemClickListener(new OnItemClickListener() {
					@Override
					public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
						// 保存选择的音乐文件
						selectMusicInfo = musicList.get(arg2);
						dialog.dismiss();
						fileName.setText(selectMusicInfo.getFileName());
					}
				});
			}
			dialog.show();
		} else {
			if(!dialog.isShowing())
				dialog.show();
		}
	}
	
	private void upload(String worksName, String introduction, String composer, String producer, String singer_status, String tv_original){
		Map<String, Object> param = new HashMap<String, Object>();
		File file = new File(selectMusicInfo.getFileUrl());
		param.put("loginname", GlobalParams.userName);
		param.put("songname", worksName);
		param.put("cover", bitmap == null ? "" : bitmap);
		param.put("songcover", introduction);
		param.put("arranger", composer);
		param.put("lyricist", producer);
		param.put("singingform", singer_status);
		param.put("originalsong", "是".equals(tv_original) ? "1" : "0");
		param.put("songsrc", file);
		param.put("lyric", lrcFile == null ? "" : lrcFile);
		param.put("token", GlobalParams.token);
		try {
			NetWorkUtils.uploadInfo(lrcFile == null ? "" : lrcFile.getName().endsWith(".krc") ? ".krc" : ".lrc", GlobalParams.UPLOAD_MUSIC_INFO, param, new RequestCallBack<String>() {
				@Override
				public void onSuccess(ResponseInfo<String> responseInfo) {
					if (loadDialog != null && loadDialog.isShowing())
						loadDialog.dismiss();
					LoggerUtils.getLog(UploadMusic.class).error(responseInfo.result);
					Toast.makeText(getActivity(), JsonUtils.getString(responseInfo.result, "message"), Toast.LENGTH_SHORT).show();
					if (JsonUtils.getString(responseInfo.result, "message").contains("成功")) {
						((EditText) getView(R.id.et_works_name)).setText("");
						((EditText) getView(R.id.et_introduction)).setText("");
						tv_lrc_name.setText("");
						tv_lrc_name.setText("");
						fileName.setText("选择歌曲");
						selectMusicInfo = null;
						lrcFile = null;
					}
				}
				@Override
				public void onFailure(HttpException error,
						String msg) {
					if (loadDialog != null && loadDialog.isShowing())
						loadDialog.dismiss();
					Toast.makeText(getActivity(), "上传失败，请重试", Toast.LENGTH_SHORT).show();
					LoggerUtils.getLog(UploadMusic.class).error(msg);
				}
			});
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (data == null) {//用户取消
			return;
		}
		if(requestCode == 0x1){
//			LoggerUtils.getLog(UploadMusic.class).error(data.getData().toString());
			if(data == null)// 用户取消
				return;
//			String dataString = Uri.decode(data.getDataString());
			String decode = Uri.decode(data.getData().getPath());
			if (decode == null)
				return;
			try{
				String[] split = decode.split(":");
				String filePath = split[split.length - 1];
				if(filePath == null)
					return;
				lrcFile = new File(data.getData().toString());
				tv_lrc_name.setText(filePath);
			}catch (Exception e) {
				lrcFile = new File(data.getData().toString());
				tv_lrc_name.setText(lrcFile.getName());
			}
		}else if(requestCode == 0x2){

			// 图片
			Uri uri = getUri(data);
			if(uri == null)
				return;
			crop(uri);
		}
		else if(requestCode == 0x4){

			// 图片
			Uri uri = getUri(data);
			if(uri == null) {
				Bitmap photo = (Bitmap) data.getExtras().get("data");
				ImgUtils.saveBitmapToSharedPreferences(getActivity(),photo);
				Bitmap photoNew=ImgUtils.getBitmapFromSharedPreferences(getActivity());
				Bitmap bitmapOK=ImgUtils.decodeSampleBitmapFromResource(getResources(),photoNew,5,5);
				((ImageView)getView(R.id.music_icon)).setImageBitmap(bitmapOK);
				return;
			}
			crop(uri);
		}
		else if(requestCode == 0x3){
			try {
    			bitmap = BitmapFactory.decodeStream(getActivity().getContentResolver().openInputStream(uritempFile));
    			((ImageView)getView(R.id.music_icon)).setImageBitmap(bitmap);
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		super.onActivityResult(requestCode, resultCode, data);
	}
	
	 /*
     * 剪切图片
     */
    private void crop(Uri uri) {
    	Intent intent = new Intent("com.android.camera.action.CROP");  
        intent.setDataAndType(uri, "image/*");  
        // crop为true是设置在开启的intent中设置显示的view可以剪裁  
        intent.putExtra("crop", "true");  
      
        // aspectX aspectY 是宽高的比例  
        intent.putExtra("aspectX", 1);  
        intent.putExtra("aspectY", 1);  
      
        // outputX,outputY 是剪裁图片的宽高  
        intent.putExtra("outputX", 250);  
        intent.putExtra("outputY", 250);  
          
        /**  
         * 此方法返回的图片只能是小图片（sumsang测试为高宽160px的图片）  
         * 故将图片保存在Uri中，调用时将Uri转换为Bitmap，此方法还可解决miui系统不能return data的问题  
         */  
        //intent.putExtra("return-data", true);        
          
        uritempFile = Uri.parse("file://" + "/" + Environment.getExternalStorageDirectory().getPath() + "/" + "xx.jpg");  
        intent.putExtra(MediaStore.EXTRA_OUTPUT, uritempFile);  
        intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());  
      
        startActivityForResult(intent, 0x3);  
    }
    
    /**  
     * 解决小米手机上获取图片路径为null的情况  
     * @param intent  
     * @return  
     */
	public Uri getUri(android.content.Intent intent) {
		Uri uri = intent.getData();
		String type = intent.getType();
		Intent openCameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
		Uri imageUri = Uri.fromFile(new File(Environment.getExternalStorageDirectory(),"image.jpg"));
		//指定照片保存路径（SD卡），image.jpg为一个临时文件，每次拍照后这个图片都会被替换

		if (imageUri!=null) {
			String path = imageUri.getEncodedPath();
            if (path != null) {
                path = imageUri.decode(path);
                ContentResolver cr = getActivity().getContentResolver();    
                StringBuffer buff = new StringBuffer();    
                buff.append("(").append(Images.ImageColumns.DATA).append("=")    
                        .append("'" + path + "'").append(")");    
                Cursor cur = cr.query(Images.Media.EXTERNAL_CONTENT_URI,    
                        new String[] { Images.ImageColumns._ID },    
                        buff.toString(), null, null);    
                int index = 0;    
                for (cur.moveToFirst(); !cur.isAfterLast(); cur.moveToNext()) {    
                    index = cur.getColumnIndex(Images.ImageColumns._ID);    
                    // set _id value    
                    index = cur.getInt(index);    
                }    
                if (index == 0) {    
                    // do nothing    
                } else {    
                    Uri uri_temp = Uri    
                            .parse("content://media/external/images/media/"    
                                    + index);    
                    if (uri_temp != null) {    
                        uri = uri_temp;    
                    }    
                }    
            }
        }    
        return uri;
    }

	public Uri showPicturePicker() {
		Intent openCameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
		Uri imageUri = Uri.fromFile(new File(Environment.getExternalStorageDirectory(), "image.jpg"));
		//指定照片保存路径（SD卡），image.jpg为一个临时文件，每次拍照后这个图片都会被替换
		openCameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
		startActivityForResult(openCameraIntent, 0x4);
		return imageUri;
	}
}
